package demos;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class DemoCache {
    volatile Map<String, Object> map = new HashMap<>();
    ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t --准备写入" + value);
            try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "\t --写入完成");
        } catch (Exception e) { e.printStackTrace(); } finally {
            lock.writeLock().unlock();
        }
    }

    public void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t ##准备读取");
            try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            Object value = map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t ##读取完成" + value);
        } catch (Exception e) { e.printStackTrace(); } finally {
            lock.readLock().unlock();
        }
    }
}

public class ReentratReadWriteLockDemo {
    public static void main(String[] args) {
        DemoCache demoCache = new DemoCache();
        for (int i = 0; i < 5; i++) {
            final int in = i;
            new Thread(() -> { demoCache.put("cache" + in, in); }, "threadW" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            final int in = i;
            new Thread(() -> { demoCache.get("cache" + in); }, "threadR" + i).start();
        }
    }
}
